const MyPromise = require('./MyPromise')

let p = new MyPromise((resolve, reject) => {
  console.log('执行器')
  resolve('正常返回')
})
p.then(res => console.log(res))

// 异步调用
let promise1 = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    resolve()
  }, 1000)
})
promise2 = promise1.then(res => {
  // 返回一个普通值
  //   return '1秒后打印普通值'

  // 返回一个MyPromise对象
  return new MyPromise((resolve, reject) => {
    setTimeout(() => {
      resolve('3秒打印，一个MyPromise')
    }, 2000)
  })
})
promise2.then(res => {
  console.log("异步打印出", res) //异步打印出
})

// then 的Fulfilled 传入一个普通字符串
promise1 = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    resolve('success')
  }, 1000)
})
promise2 = promise1.then('这里的onFulfilled本来是一个函数，但现在不是')
promise2.then(res => {
  console.log(" 1秒后打印出:",res) // 1秒后打印出：success
}, err => {
  console.log(err)
})

// // then onReject传入普通字符串， promise2接收到的值是1 reject传入的值，并不是then中传入的普通值，普通纸会被忽略
promise1 = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    // resolve('success')
    reject('fail')
  }, 1000)
})
promise2 = promise1.then(res => res, '应该是一个函数，所以被忽略')
promise2.then(res => {
  console.log("打印异步的返回",res)
}, err => {
  console.log(err) // 1秒后打印出：fail
  throw new Error('异常')
}).catch(err => {
    console.log('catch', err)
}).finally(res => {
    console.log('finally', res)
})

let r1 = MyPromise.resolve('123')
let r2 = MyPromise.resolve('456')
let r3 = MyPromise.resolve('789')

MyPromise.all([r1,r2,r3]).then((res) => {
    console.log("success MyPromise.all", res)
})

MyPromise.race([r1,r2,r3]).then((res) => {
    console.log("success MyPromise.race", res)
})

r1 = MyPromise.reject('error MyPromise.all')
MyPromise.all([r1,r2,r3]).then((res) => {
    console.log("success all", res)
},res => {
    console.log("error all", res)
})



r1 = MyPromise.reject('error MyPromise.race')
r2 = MyPromise.reject('error MyPromise.race')
r3 = MyPromise.reject('error MyPromise.race')
MyPromise.all([r1,r2,r3]).then((res) => {
    console.log("success race", res)
},res => {
    console.log("error race", res)
})
